#include "mainwindow.h"
#include "mapcanvas.h"
#include <QToolBar>
#include <QAction>
#include <QFileDialog>
#include <QtDebug>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle("Qt Map Editor");
    resize(1000, 700);

    m_view = new MapCanvas(this);
    setCentralWidget(m_view);

    QToolBar *tb = addToolBar("Tools");
    QAction *a;

    a = tb->addAction("Select");
    connect(a, &QAction::triggered, this, &MainWindow::onSelect);

    a = tb->addAction("Point");
    connect(a, &QAction::triggered, this, &MainWindow::onAddPoint);

    a = tb->addAction("Line");
    connect(a, &QAction::triggered, this, &MainWindow::onAddLine);

    a = tb->addAction("Polygon");
    connect(a, &QAction::triggered, this, &MainWindow::onAddPolygon);

    tb->addSeparator();
    a = tb->addAction("Save GeoJSON");
    connect(a, &QAction::triggered, this, &MainWindow::onSave);

    auto *zoomBar = new QToolBar("Zoom", this);
    auto *zoomIn  = zoomBar->addAction("+");
    auto *zoomOut = zoomBar->addAction("-");
    addToolBar(Qt::TopToolBarArea, zoomBar);
    connect(zoomIn,  &QAction::triggered, this, [this]{ m_view->setZoom(m_view->zoom()+1); });
    connect(zoomOut, &QAction::triggered, this, [this]{ m_view->setZoom(m_view->zoom()-1); });
}

void MainWindow::onSelect()   { m_view->setTool(MapCanvas::Select); }
void MainWindow::onAddPoint() { m_view->setTool(MapCanvas::AddPoint); }
void MainWindow::onAddLine()  { m_view->setTool(MapCanvas::AddLine); }
void MainWindow::onAddPolygon(){ m_view->setTool(MapCanvas::AddPolygon); }

void MainWindow::onSave()
{
    QString file = QFileDialog::getSaveFileName(this, "Save", "", "GeoJSON (*.geojson)");
    if (!file.isEmpty())
        m_view->exportGeoJson(file);
}
